import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { ConfirmationService, Message, SelectItem } from 'primeng/api';
import { MessageService } from 'primeng/components/common/messageservice';
import { ProjectService } from '../../service/project.service';
import { CountryUtilsService } from '../../../shared/services/country-utils.service';
import { ConstantVariable, UserRoles, PropertySaleStatus, PropertyType } from '../../../shared/config/app-settings';
import { FileUpload } from 'primeng/fileupload';
import { PropertyService } from '../../service/property.service';
import * as _ from 'lodash';
import { AttachmentUtilsService } from '../../../shared/services/attachment-utils.service';
import { UserService } from '../../../shared/services/user.service';
import { MessageUtilsService } from '../../../shared/services/message-utils.service';
import { SolicitorService } from '../../../layout/admin/service/solicitor.service';
@Component({
  selector: 'app-property-detail-house-edit',
  templateUrl: './property-detail-house-edit.component.html',
  styleUrls: ['./property-detail-house-edit.component.css']
})
export class PropertyDetailHouseEditComponent implements OnInit {
  PropertySaleStatus = PropertySaleStatus;
  PropertyType = PropertyType;

  @Input() id;
  property: any = {};
  purchaseDate: Date;
  commenceDate: Date;
  saleStatus: string;

  //controls
  //parent property list
  propertylistsOptions: SelectItem[];
  selectedPropertyList: any = {};
  //owner
  ownersOptions: SelectItem[];
  selectedOwner: any = {};
  //agent
  agentsOptions: SelectItem[];
  selectedAgent: any = {};
  //solicitor
  solicitorsOptions: SelectItem[];
  selectedSolicitor: any = {};
  // aspect
  aspectOptions: SelectItem[];
  selectedAspect: any;


  msgs: Message[] = [];

  constructor(private confirmationService: ConfirmationService,
    private propertyService: PropertyService,
    private userService: UserService,
    private solicitorService: SolicitorService,
    private attachmentUtilsService: AttachmentUtilsService,
    private projectService: ProjectService,
    private messageUtilsService: MessageUtilsService,
    private countryUtilsService: CountryUtilsService) { }

  ngOnInit() {
    this.initProperty();
  }



  onSave() {
    this.updateProperty();
  }

  initProperty() {
    if (this.id === 0) {
      this.property = {};
      this.initDropDowns();
    } else {
      this.loadPropertyDetail(this.id);

    }
  }

  loadPropertyDetail(id) {
    this.propertyService.getPropertyById(id).subscribe(
      (res) => {

        this.property = res;
        this.enrichResponse();
        this.initDropDowns();
        // this.propertyStatus = this.propertylist['status'] === 'active' ? true : false;
      });
  }

  updateProperty() {
    let finalProperty = this.constructorPostBody();
    console.log(finalProperty);
    this.propertyService.updateProperty(finalProperty).subscribe(
      (res) => {
        console.log(res);
        this.id = res.data.id;
        this.initProperty();
        this.messageUtilsService.showInfo(this.msgs, res.msg);
      },
      (err) => {
        console.log(err);
        this.messageUtilsService.showInfo(this.msgs,err.msg);
      }
    )
  }


  initDropDowns() {
    //propertylists
    this.projectService.getAllPropertyLists().subscribe(
      (res) => {
        this.propertylistsOptions = [{ label: 'None', value: {} }];
        this.selectedPropertyList = {};
        _.each(res, (item) => {
          let option = { label: this.projectService.getShortName(item), value: item };
          this.propertylistsOptions.push(option);
          if (this.property.propertyListId === item.id) {
            this.selectedPropertyList = item;
          }

        });
      });

    //owners
    this.userService.loadUserList(UserRoles.CUSTOMER).subscribe(
      (res) => {
        this.ownersOptions = [{ label: 'None', value: {} }];
        this.selectedOwner = {};
        _.each(res, (item) => {
          let option = { label: this.userService.getFullName(item), value: item }
          this.ownersOptions.push(option);
          if (this.property.ownerId === item.id) {
            this.selectedOwner = item;
          }
        });
      });
    // solicitor
    this.solicitorService.loadSolicitors().subscribe(
      (res) => {
        this.solicitorsOptions = [{ label: 'None', value: {} }];
        this.selectedSolicitor = {};
        _.each(res, (item) => {
          let option = { label: item.company, value: item };
          this.solicitorsOptions.push(option);
          if (this.property.solicitorId === item.id) {
            this.selectedSolicitor = item;
          }
        });
      });
    //agents
    this.userService.loadUserList(UserRoles.AGENT).subscribe(
      (res) => {
        this.agentsOptions = [{ label: 'None', value: {} }];
        this.selectedAgent = {};
        _.each(res, (item) => {
          let option = { label: this.userService.getFullName(item), value: item }
          this.agentsOptions.push(option);
          if (this.property.agentId === item.id) {
            this.selectedAgent = item;
          }


        });
        console.log(this.selectedAgent);
      });

      this.aspectOptions = [
        { label: 'N', value: 'N' },
        { label: 'W', value: 'W' },
        { label: 'S', value: 'S' },
        { label: 'E', value: 'E' },
        { label: 'NW', value: 'NW' },
      ]
      _.each(this.aspectOptions, (item) => {
        if(this.property.aspect === item.value) {
          this.selectedAspect = item;
        }
      });

      this.selectedAspect = this.property.aspect;


  }

  saleStatusChange(newStatus){
    console.log("target status {}", newStatus);
    this.propertyService.updateSalesStatus({id:this.property.id, 'sale-status':newStatus}).subscribe(
      res=>{
        this.loadPropertyDetail(this.property.id);
        this.messageUtilsService.showInfo(this.msgs, "status changed to:"+this.property.sale_status);
      },
      err=>{
        console.log(err);
      }
    )

    
  }

  fileUpload(belongToCategory, fileUploader, entity, deleteOrigin=false) {
    if(this.id === 0){
      this.messageUtilsService.showError(this.msgs,"Please save project first before upload files");
      return;
    }
    
    let attachment = {
      entity: entity,
      belongToID: entity.id,
      belongToCategory: belongToCategory,
      files: fileUploader.files
    };
    this.attachmentUtilsService.uploadFile(attachment, deleteOrigin).subscribe(
      (res) => {
        this.messageUtilsService.showInfo(this.msgs," Attahement update success");
        fileUploader.clear();
        this.property[belongToCategory] = res.data;
      },
      (err) => {
        console.log(err);
        this.messageUtilsService.showError(this.msgs,"Operation Failed.");
      }
    );
  }

  deleteFile(attachment) {
    this.attachmentUtilsService.deleteAttachment(attachment).subscribe(
      (res) => {
        this.messageUtilsService.showInfo(this.msgs,attachment.originalFilename + " delete success");
        this.property[attachment.belongToCategory] = res['data'];
        // this.initPropertyList();
      },
      (err) => {
        console.log(err);
        this.messageUtilsService.showError(this.msgs,"Operation Failed.");
      }
    );
  }

  //utils
  enrichResponse() {
    this.propertyService.escapeAll(this.property, false);
    this.purchaseDate = this.property.purchaseDate ? new Date(this.property.purchaseDate) : null;
    this.commenceDate = this.property.commenceDate ? new Date(this.property.commenceDate) : null
  }

  constructorPostBody() {
    let resultProperty = _.cloneDeep(this.property);
    resultProperty.propertyListId = _.isEmpty(this.selectedPropertyList) ? 0 : this.selectedPropertyList.id;
    resultProperty.ownerId = _.isEmpty(this.selectedOwner) ? 0 : this.selectedOwner.id;
    if(resultProperty.agentId>0 && _.isEmpty(this.selectedAgent)){
      this.resetPropertyToForSale(resultProperty);
    }
    resultProperty.agentId = _.isEmpty(this.selectedAgent) ? 0 : this.selectedAgent.id;
    resultProperty.solicitorId = _.isEmpty(this.selectedSolicitor) ? 0 : this.selectedSolicitor.id;
    resultProperty.purchaseDate = this.purchaseDate || null;
    resultProperty.commenceDate = this.commenceDate || null;
    return resultProperty;

  }

  getPictures() {
    return this.property['property_main_image'] || [];
  }

  getFullName(user) {
    return user ? this.userService.getFullName(user) : 'Nobody';
  }

  getFullAddress(project){
    return this.projectService.getFullAddress(project);
  }

  //utils
  resetPropertyToForSale(property){
    property.sale_note = '';
    property.agentId = 0;
    property.purchaseDate = '';
    property.sellingPrice = '';
    property.total_commission_sale = '';
    property.current_commission_sale  = '';
    let attachmentIDs = _.map(property.property_bank_card_picture, 'id');
    this.attachmentUtilsService.deleteByIDs(attachmentIDs).subscribe(
      (res) => {
        console.log(res);
      },
      (err) => {
        console.error(err);
      });
  }





}
